import { Request, Response, NextFunction } from 'express';
import { getCachedPrisma, prisma } from '../../config/database';
import { CACHE_PREFIXES, CACHE_TTL, deleteCacheByPattern } from '../../config/redis';
import { logger } from '../../utils/logger';
import { BaseController } from '../../utils/autoBind';
import { ResponseUtils } from '../../utils/responseUtils';
import { BUSINESS_ERROR_CODES, VALIDATION_ERROR_CODES } from '../../utils/errorCodes';
import { getFileUrl, deleteFile } from '../../middleware/upload';

export class ArtistController extends BaseController {
  // 获取艺人列表
  async getArtists(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { page = 1, limit = 20, status, search } = req.query;
      const pageNum = parseInt(page as string);
      const limitNum = parseInt(limit as string);
      const skip = (pageNum - 1) * limitNum;

      // 构建查询条件
      const where: any = {};
      
      if (status) {
        where.status = status;
      }
      
      if (search) {
        where.OR = [
          { name: { contains: search as string } },
          { description: { contains: search as string } },
          { country: { contains: search as string } }
        ];
      }

      // 查询艺人列表
      const [artists, total] = await Promise.all([
        prisma.artist.findMany({
          where,
          skip,
          take: limitNum,
          orderBy: { createdAt: 'desc' },
          include: {
            _count: {
              select: {
                performances: true,
                votes: true,
                works: true
              }
            }
          }
        }),
        prisma.artist.count({ where })
      ]);

      // 格式化响应数据
      const formattedArtists = artists.map((artist: any) => ({
        id: artist.id,
        name: artist.name,
        description: artist.description,
        avatar: artist.avatar,
        bannerImage: artist.bannerImage,
        genre: artist.genre,
        country: artist.country,
        status: artist.status,
        createdAt: artist.createdAt,
        updatedAt: artist.updatedAt,
        stats: {
          performanceCount: artist._count.performances,
          voteCount: artist._count.votes,
          workCount: artist._count.works
        }
      }));

      ResponseUtils.paginated(res, formattedArtists, total, pageNum, limitNum, '获取艺人列表成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取艺人详情
  async getArtist(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const artistId = parseInt(id);

      if (isNaN(artistId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的艺人ID');
        return;
      }

      // 获取缓存 Prisma 客户端
      const cachedPrisma = await getCachedPrisma();

      const artist = await cachedPrisma.artist.findUnique({
        where: { id: artistId },
        include: {
          performances: {
            orderBy: { startTime: 'asc' }
          },
          votes: {
            include: {
              user: {
                select: {
                  id: true,
                  username: true,
                  realName: true,
                  avatar: true
                }
              }
            }
          },
          works: {
            orderBy: { createdAt: 'desc' }
          },
          trivia: {
            where: { isActive: true },
            orderBy: { createdAt: 'desc' }
          },
          _count: {
            select: {
              performances: true,
              votes: true,
              works: true,
              trivia: true
            }
          }
        },
        cache: {
          ttl: CACHE_TTL.ARTIST_DETAIL,
          key: `${CACHE_PREFIXES.ARTIST_DETAIL}${artistId}`,
        }
      });

      if (!artist) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ARTIST_NOT_FOUND, '艺人不存在');
        return;
      }

      ResponseUtils.success(res, artist, '获取艺人详情成功');
    } catch (error) {
      next(error);
    }
  }

  // 创建艺人
  async createArtist(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { name, description, avatar, bannerImage, country } = req.body;

      // 验证必填字段
      if (!name) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ARTIST_NAME_EMPTY, '艺人名称不能为空');
        return;
      }

      // 检查艺人名称是否已存在
      const existingArtist = await prisma.artist.findFirst({
        where: { name }
      });

      if (existingArtist) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ARTIST_ALREADY_EXISTS, '艺人名称已存在');
        return;
      }

      const artist = await prisma.artist.create({
        data: {
          name,
          description,
          avatar,
          bannerImage,
          country
        }
      });

      logger.info(`艺人创建成功: ${artist.name} (ID: ${artist.id})`);
      ResponseUtils.created(res, artist, '创建艺人成功');
    } catch (error) {
      next(error);
    }
  }

  // 更新艺人信息
  async updateArtist(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const artistId = parseInt(id);
      const { name, description, avatar, bannerImage, country, status } = req.body;

      if (isNaN(artistId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的艺人ID');
        return;
      }

      // 获取缓存 Prisma 客户端
      const cachedPrisma = await getCachedPrisma();

      // 检查艺人是否存在
      const existingArtist = await cachedPrisma.artist.findUnique({
        where: { id: artistId },
        cache: {
          ttl: CACHE_TTL.ARTIST_INFO,
          key: `${CACHE_PREFIXES.ARTIST_INFO}${artistId}`,
        }
      });

      if (!existingArtist) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ARTIST_NOT_FOUND, '艺人不存在');
        return;
      }

      // 如果更新名称，检查是否与其他艺人重名
      if (name && name !== existingArtist.name) {
        const nameConflict = await prisma.artist.findFirst({
          where: {
            name,
            id: { not: artistId }
          }
        });

        if (nameConflict) {
          ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ARTIST_ALREADY_EXISTS, '艺人名称已存在');
          return;
        }
      }

      const updatedArtist = await cachedPrisma.artist.update({
        where: { id: artistId },
        data: {
          name,
          description,
          avatar,
          bannerImage,
          country,
          status
        },
        cache: {
          ttl: CACHE_TTL.ARTIST_INFO,
          key: `${CACHE_PREFIXES.ARTIST_INFO}${artistId}`,
        }
      });
      deleteCacheByPattern(`${CACHE_PREFIXES.ARTIST_DETAIL}${artistId}`);

      logger.info(`艺人更新成功: ${updatedArtist.name} (ID: ${updatedArtist.id})`);
      ResponseUtils.updated(res, updatedArtist, '更新艺人信息成功');
    } catch (error) {
      next(error);
    }
  }

  // 删除艺人
  async deleteArtist(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const artistId = parseInt(id);

      if (isNaN(artistId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的艺人ID');
        return;
      }

      // 获取缓存 Prisma 客户端
      const cachedPrisma = await getCachedPrisma();

      // 检查艺人是否存在
      const artist = await cachedPrisma.artist.findUnique({
        where: { id: artistId },
        include: {
          _count: {
            select: {
              performances: true,
              votes: true
            }
          }
        }
      });

      if (!artist) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ARTIST_NOT_FOUND, '艺人不存在');
        return;
      }

      // 检查是否有关联数据
      if (artist._count.performances > 0) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.OPERATION_NOT_ALLOWED, '该艺人还有演出安排，无法删除');
        return;
      }

      if (artist._count.votes > 0) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.OPERATION_NOT_ALLOWED, '该艺人还有投票数据，无法删除');
        return;
      }

      await cachedPrisma.artist.delete({
        where: { id: artistId },
        cache: {
          key: `${CACHE_PREFIXES.ARTIST_INFO}${artistId}`,
        }
      });
      deleteCacheByPattern(`${CACHE_PREFIXES.ARTIST_DETAIL}${artistId}`);

      logger.info(`艺人删除成功: ${artist.name} (ID: ${artistId})`);
      ResponseUtils.deleted(res, '删除艺人成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取艺人统计信息
  async getArtistStatistics(_req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      // 获取缓存 Prisma 客户端
      const cachedPrisma = await getCachedPrisma();

      const [
        totalArtists,
        activeArtists,
        totalPerformances,
        totalVotes,
        topArtists
      ] = await Promise.all([
        // 总艺人数量
        prisma.artist.count(),
        
        // 活跃艺人数量
        prisma.artist.count({
          where: { status: 'ACTIVE' }
        }),
        
        // 总演出数量
        prisma.performance.count(),
        
        // 总投票数量
        prisma.vote.count(),
        
        // 热门艺人（按投票数）
        cachedPrisma.artist.findMany({
          take: 10,
          orderBy: {
            votes: {
              _count: 'desc'
            }
          },
          include: {
            _count: {
              select: {
                votes: true,
                performances: true
              }
            }
          },
          cache: {
            ttl: CACHE_TTL.ARTIST_LIST,
            key: `${CACHE_PREFIXES.ARTIST_LIST}`,
          }
        })
      ]);

      const statistics = {
        overview: {
          totalArtists,
          activeArtists,
          totalPerformances,
          totalVotes
        },
        topArtists: topArtists.map((artist: any) => ({
          id: artist.id,
          name: artist.name,
          voteCount: artist._count.votes,
          performanceCount: artist._count.performances
        }))
      };

      ResponseUtils.success(res, statistics, '获取艺人统计信息成功');
    } catch (error) {
      next(error);
    }
  }

  // 上传艺人头像
  async uploadAvatar(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const artistId = parseInt(id);

      if (isNaN(artistId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的艺人ID');
        return;
      }

      if (!req.file) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.REQUIRED_FIELD_MISSING, '请选择要上传的头像文件');
        return;
      }

      // 获取缓存 Prisma 客户端
      const cachedPrisma = await getCachedPrisma();

      // 检查艺人是否存在
      const artist = await cachedPrisma.artist.findUnique({
        where: { id: artistId },
        cache: {
          ttl: CACHE_TTL.ARTIST_INFO,
          key: `${CACHE_PREFIXES.ARTIST_INFO}${artistId}`,
        }
      });

      if (!artist) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ARTIST_NOT_FOUND, '艺人不存在');
        return;
      }

      // 删除旧头像
      if (artist.avatar) {
        const oldFilename = artist.avatar.split('/').pop();
        if (oldFilename) {
          deleteFile(oldFilename, 'avatar');
        }
      }

      // 更新艺人头像
      const avatarUrl = getFileUrl(req.file.filename, 'avatar');
      const updatedArtist = await cachedPrisma.artist.update({
        where: { id: artistId },
        cache: {
          ttl: CACHE_TTL.ARTIST_INFO,
          key: `${CACHE_PREFIXES.ARTIST_INFO}${artistId}`,
        },
        data: { avatar: avatarUrl }
      });
      deleteCacheByPattern(`${CACHE_PREFIXES.ARTIST_DETAIL}${artistId}`);

      logger.info(`艺人头像上传成功: ${artist.name} (ID: ${artistId})`);
      ResponseUtils.success(res, updatedArtist, '头像上传成功');
    } catch (error) {
      next(error);
    }
  }

  // 上传艺人横幅图片
  async uploadBanner(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const artistId = parseInt(id);

      if (isNaN(artistId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的艺人ID');
        return;
      }

      if (!req.file) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.REQUIRED_FIELD_MISSING, '请选择要上传的横幅图片文件');
        return;
      }

      // 获取缓存 Prisma 客户端
      const cachedPrisma = await getCachedPrisma();

      // 检查艺人是否存在
      const artist = await cachedPrisma.artist.findUnique({
        where: { id: artistId },
        cache: {
          ttl: CACHE_TTL.ARTIST_INFO,
          key: `${CACHE_PREFIXES.ARTIST_INFO}${artistId}`,
        }
      });

      if (!artist) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ARTIST_NOT_FOUND, '艺人不存在');
        return;
      }

      // 删除旧横幅
      if (artist.bannerImage) {
        const oldFilename = artist.bannerImage.split('/').pop();
        if (oldFilename) {
          deleteFile(oldFilename, 'banner');
        }
      }

      // 更新艺人横幅
      const bannerUrl = getFileUrl(req.file.filename, 'banner');
      const updatedArtist = await cachedPrisma.artist.update({
        where: { id: artistId },
        cache: {
          ttl: CACHE_TTL.ARTIST_INFO,
          key: `${CACHE_PREFIXES.ARTIST_INFO}${artistId}`,
        },
        data: { bannerImage: bannerUrl }
      });

      deleteCacheByPattern(`${CACHE_PREFIXES.ARTIST_DETAIL}${artistId}`);
      logger.info(`艺人横幅上传成功: ${artist.name} (ID: ${artistId})`);
      ResponseUtils.success(res, updatedArtist, '横幅上传成功');
    } catch (error) {
      next(error);
    }
  }
} 